//
//  LinkServers.m
//  HGMMT
//
//  Created by xingweixin on 2018/4/16.
//  Copyright © 2018年 eport_user1. All rights reserved.
//

#import "LinkServers.h"

#import "DeviceInfo.h"
#import "LYYTabBarViewController.h"
#import "Tool.h"
#import "NSString+Format.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MBProgressHUD+NJ.h"


static LinkServers *instance = nil;

@interface LinkServers ()<GCDAsyncSocketDelegate>{
    
    SystemSoundID scoreClickBtnID;
}


@property(nonatomic,assign)BOOL connected;
@property (nonatomic, strong) NSTimer *connectTimer;
@property(nonatomic,copy)NSString *ideCode;

@end

@implementation LinkServers


//创建一个单利
+ (LinkServers *)shareInstance{
    
    @synchronized (self) {
        
        if (instance == nil) {
            
            instance = [[LinkServers alloc]init];
        }
        
        return instance;
    }
}

-(instancetype)init{
    self = [super init];
    if (self) {
        
        self.clientSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        
    }
    return self;
}


-(void)linkWithIdeCode:(NSString *)code{

    self.ideCode = code;
    code = [code formatIpPorts];
    NSArray *array = [code componentsSeparatedByString:@":"];
    NSString *host = array[0];
    NSInteger port = [array[1] integerValue];
    
    [MBProgressHUD showMessage:@"正在连接"];
    self.connected = [self.clientSocket connectToHost:host onPort:port error:nil];
    
}

//将间接成功的ide识别码放入数据库中
-(void)saveDataToUserDefeat:(NSString *)code{
    
    NSArray *array = [[NSUserDefaults standardUserDefaults]objectForKey:SQLITEDEFEATS];
    NSMutableArray *mutaArray;
    if (array)
    {
        mutaArray = [NSMutableArray arrayWithArray:array];
    }
    else
    {
        mutaArray = [NSMutableArray array];
    }
    
    
    for (NSString *str in array) {
        
        if ([str isEqualToString:code]) {
            [mutaArray removeObject:str];
        }
    }
    
    [mutaArray addObject:code];
    
    NSUserDefaults *defeats = [NSUserDefaults standardUserDefaults];
    
    [defeats setObject:mutaArray forKey:SQLITEDEFEATS];
   
    //数据同步
    [defeats synchronize];
    
    
}


#pragma mark -代理方法
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    
    HGLog(@"链接成功");
    
    [MBProgressHUD hideHUD];
    
    [self saveDataToUserDefeat:self.ideCode];
    self.linkhost = host;
    
    if (self.linkBlock) {
        
        self.linkBlock(YES);
    }
    
    
    NSDictionary *dix = [DeviceInfo getDeviceInfo];
    
    NSString *string1 = [Tool convertToJsonData:dix];
    
    NSString *string2 = [NSString stringWithFormat:@"-N:%@\n",string1];
    
    NSData *dataxx = [string2 dataUsingEncoding:NSUTF8StringEncoding];
    [self.clientSocket writeData:dataxx withTimeout:-1 tag:0];
    
    
    HGLog(@"数据发送成功");
    
    // 连接成功开启定时器
    //[self addTimer];
    
    // 连接后,可读取服务端的数据
    [self.clientSocket readDataWithTimeout:- 1 tag:0];
    self.connected = YES;
    
    
    //跳转到主页
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    LYYTabBarViewController *lyyMian = [[LYYTabBarViewController alloc]init];
    keyWindow.rootViewController = lyyMian;
    
    //播放声音
    [self playAudio];
    
    //发送请求插件列表
    
  

}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(nullable NSError *)err{
    
    HGLog(@"链接失败");
    [MBProgressHUD hideHUD];
    
    if (self.linkBlock) {
        
        self.linkBlock(NO);
    }
    
    //断开连接发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:Link_Disconnect object:self userInfo:nil];

    
}


-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    
    
    if (self.communBlock) {
        
        self.communBlock(data);
    }
    
    [self.clientSocket readDataWithTimeout:- 1 tag:0];
    self.connected = YES;
    
    HGLog(@"接收到数据");
    
}


// 添加定时器
- (void)addTimer
{
    // 长连接定时器
    self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];
    // 把定时器添加到当前运行循环,并且调为通用模式
    [[NSRunLoop currentRunLoop] addTimer:self.connectTimer forMode:NSRunLoopCommonModes];
}

// 心跳连接
- (void)longConnectToSocket
{
    // 发送固定格式的数据,指令@"longConnect"
    float version = [[UIDevice currentDevice] systemVersion].floatValue;
    NSString *longConnect = [NSString stringWithFormat:@"123%f",version];
    
    NSData  *data = [longConnect dataUsingEncoding:NSUTF8StringEncoding];
    
    [self.clientSocket writeData:data withTimeout:- 1 tag:0];
}

//断开连接
-(void)disConnectSocket{
    [self.clientSocket disconnect];
    [self.connectTimer invalidate];
    self.connectTimer = nil;

}

//播放声音
-(void)playAudio{
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)([NSURL fileURLWithPath:[NSString stringWithFormat:@"/System/Library/Audio/UISounds/new-mail.caf"]]), &scoreClickBtnID);
    
   AudioServicesPlaySystemSound(scoreClickBtnID);
    
   AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

@end
